<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\AdminUser;
use Omnipay\Omnipay;
use Overtrue\EasySms\Exceptions\Exception;
use think\Controller;
use think\Db;
use think\Request;

class Finance extends Base
{

    /**
     * @param Request $request
     * @return \think\response\View
     * 审核列表
     */
    public function index(Request $request)
    {

        $limit      = $request->param('limit') ?: 10;
        $page       = $request->param('page') ?: 1;
        $start_time = $request->param('start_time') ?: '';
        $end_time   = $request->param('end_time') ?: '';
        $keyword    = trim($request->param('keyword')) ?: '';
        $position   = $request->session('finance_permission');
        $status     = $request->param('status') ?: 1;
        //待处理的才是待办
        if ($position && $status == 1) {
            $where['progress'] = $position;
            $where['status']   = $status;
        } else {
            $where['status'] = $status;
        }
        if ($status == 4) {
            $where['status']   = 1;
            $where['progress'] = ['NEQ', $position];
        }

        $where_other = [];
        if ($start_time && $end_time) {
            $time1                      = strtotime($start_time);
            $time2                      = strtotime($end_time);
            $where['create_time']       = ['between', "$time1,$time2"];
            $where_other['create_time'] = ['between', "$time1,$time2"];
        }

        if ($keyword) {
            $where['username|mobile'] = ['like', "%{$keyword}%"];
        }

        $finance_list = Db::table('ad_finance')->where($where)->order(['create_time' => 'asc'])->paginate($limit,
            false,
            [
                'page' => $page,
                'query' => [
                    'keyword' => $keyword,
                    'start_time' => $start_time,
                    'end_time' => $end_time,
                    'status' => $status
                ]
            ])->each(function ($item, $key) {
            $item['progress']        = getProGressName($item['progress']);
            $item['status']          = getWithDrawStatus($item['status']);
            $item['create_time']     = date('Y-m-d H:i:s', $item['create_time']);
            $item['withdraw_days']   = (int)date('m', time() - strtotime($item['create_time']));
            $item['withdraw_way']    = getWithDrawWay($item['withdraw_way']);
            $item['withdraw_status'] = getWithStatus($item['withdraw_status']);
            return $item;
        });


        $recharge = Db::table('ad_user_money')->where($where_other)->where(['status' => 1])->sum('money');
        $withdraw = Db::table('ad_finance')->where($where_other)->where(['withdraw_status' => 1])->sum('withdraw_money');
        $column   = [
            1 => '待审核',
            2 => '审核不通过',
            3 => '审核通过',
            4 => '正在处理',
        ];
        return view('list',
            compact('finance_list', 'keyword', 'start_time', 'end_time', 'status', 'recharge', 'withdraw', 'column'));
    }


    /**
     * @param Request $request
     * 审核详细
     */
    public function financeDetail(Request $request)
    {

        $finance_id              = $request->param('finance_id');
        $finance_data            = Db::table('ad_finance')->find($finance_id);
        $finance_data['suggest'] = Db::table('ad_finance_suggest')->where(['finance_id' => $finance_data['id']])->select();


        return json(['code' => 200, 'info' => '已获取到数据', 'data' => $finance_data]);
    }


    /**
     * @param Request $request
     * @return \think\response\View
     * 审核详细
     */
    public function info(Request $request)
    {

        $finance_id   = $request->param('id');
        $finance_data = Db::table('ad_finance')->find($finance_id);

        $finance_data['suggest']       = Db::table('ad_finance_suggest')->where(['finance_id' => $finance_data['id']])->select();
        $finance_data['progress_name'] = getProGressName($finance_data['progress']);
        $finance_data['status_name']   = getWithDrawStatus($finance_data['status']);

        $finance_data['apply_time'] = date('Y-m-d H:i:s', $finance_data['create_time']);
        $finance_data['percent']    = getProGressPercent($finance_data['progress'], $finance_data['status']);

        $finance_data['bank_status']     = empty($this->verifyBank($finance_data['bank_card_num'],
            $finance_data['bank_code'])) ? '不一致' : '一致';

        $bank_verify = Db::table('ad_bank_verify')->where([
            'uid' => $finance_data['uid'],
            'status' => 1,
            'card_num' => $finance_data['bank_card_num']
        ])->order(['create_time' => 'desc'])->find();

        $finance_data['mobile'] = $bank_verify['phone'];

        //充值详细
        $result                     = Db::table('ad_user_money')->where([
            'uid' => $finance_data['uid'],
            'status' => 1
        ])->select();
        $user_info                  = Db::table('ad_user_info')->where(['uid' => $finance_data['uid']])->find();
        $user_info['province_name'] = Db::table('ad_provinces')->where(['provinceid' => $user_info['province']])->value('province');
        $user_info['city_name']     = Db::table('ad_cities')->where(['cityid' => $user_info['city']])->value('city');

        foreach ($result as $item => $value) {
            $result[$item]['province_name'] = $user_info['province_name'];
            $result[$item]['city_name']     = $user_info['city_name'];
            $result[$item]['true_name']     = $user_info['true_name'];
            $result[$item]['phone']         = $bank_verify['phone'];
            $result[$item]['ID_card']       = $bank_verify['id_card'];
        }

        //自媒体收入
        $weMediaIncome = Db::table('ad_lcb')->where(['uid' => $finance_data['uid']])->field([
            'SUM(money)' => 'money_sum',
            'channel'
        ])->group('channel')->select();

        //看进行到哪一步了
        $finance_info = Db::table('ad_finance')->find($finance_id);
        if (empty($finance_info)) {
            $this->error('找不到提现单号');
        }
        foreach ($finance_data['suggest'] as $item => $value) {
            $admin_user                                   = Db::table('ad_finance_user')->find($value['finance_user_id']);
            $finance_data['suggest'][$item]['check_name'] = empty($admin_user) ? '' : $admin_user['user_name'];
        }
        $data['finance_user_id']    = $request->session('auth_id');
        $finance_data['check_name'] = Db::table('ad_finance_user')->find($request->session('auth_id'))['user_name'];

        $data_rate              = Db::table('ad_extract')->find(1)['extract_poundage'];//找到费率
        $rate                   = $data_rate / 100;
        $finance_data['deduct'] = ($finance_data['coin'] * $rate) / 100;

        //看提交的人有没有修改的权限
        $position = $position = Db::table('ad_finance_user')->find($data['finance_user_id'])['finance_permission'];

        if ($position != $finance_info['progress']) {
            $this->error('您不能进行此操作');
        }

        return view('edit', compact('finance_data', 'weMediaIncome', 'result'));

    }

    /**
     * @param Request $request
     * 提交审核
     */
    public function update(Request $request)
    {
        $data['finance_id']      = $request->param('id');
        $data['suggest']         = $request->param('comment');
        $data['status']          = $request->param('status');
        $data['create_time']     = $data['update_time'] = time();
        $data['finance_user_id'] = $request->session('auth_id');


        //看进行到哪一步了
        $finance_data = Db::table('ad_finance')->find($data['finance_id']);
        if (empty($finance_data)) {
            $this->error('找不到提现单号');
        }
        //看提交的人有没有修改的权限
        $position = $position = $request->session('finance_permission');

        if ($position != $finance_data['progress']) {
            $this->error('还没进行到您的提交');
        }

        if ($finance_data['is_handle'] == 1) {
            if ($finance_data['progress'] == 1 && $finance_data['status'] == 2) {
                $this->error('初审不通过,提现已驳回');
            }
            if ($finance_data['progress'] == 2 && $finance_data['status'] == 2) {
                $this->error('复审不通过,提现已驳回');
            }
            if ($finance_data['progress'] == 3 && $finance_data['status'] == 2) {
                $this->error('财务审核不通过,提现已驳回');
            }
            if ($finance_data['progress'] == 3 && $finance_data['status'] == 3) {
                $this->error('财务审核通过,提现已完成');
            }
            $this->error('财务已最终处理过,或者该提现已驳回');
        }

        //不通过
        if ($data['status'] == 2) {
            $result_1 = Db::table('ad_finance')->where(['id' => $data['finance_id']])->update([
                'progress' => $finance_data['progress'],
                'status' => $data['status'],
                'is_handle' => 1,
                'update_time' => time()
            ]);
            if ($result_1) {
                $ad_extract       = Db::table('ad_extract')->where('id', 1)->find();
                $extract_poundage = $ad_extract['extract_poundage'];
//                $return_money     = $finance_data['withdraw_money'] * (1 + ($extract_poundage / 100));
                $return_money = $finance_data['coin'];
                //todo 不通过的话,要退龙彩币,再让前端发起请求
                $result = Db::table('ad_user_info')->where(['uid' => $finance_data['uid']])->setInc(
                    'earn', $return_money
                );
            }
        } else {
            //通过
            if ($finance_data['progress'] == 3) {
                $result = Db::table('ad_finance')->where(['id' => $data['finance_id']])->update([
                    'progress' => $finance_data['progress'],
                    'status' => $data['status'],
                    'is_handle' => 1,
                    'update_time' => time()
                ]);
                //最终通过,直接打钱到银行卡
                if ($result) {
                    $this->withdraw_wechat($data['finance_id']);
                }
            } else {
                $result = Db::table('ad_finance')->where(['id' => $data['finance_id']])->update([
                    'progress' => $finance_data['progress'] + 1,
                    'status' => 1
                ]);
            }
        }

        $result_log = Db::table('ad_finance_suggest')->insert($data);
        if ($result && $result_log) {
            return '处理成功';
//            $this->success('处理成功');
        }
        $this->error('提交失败');
    }


    /**
     * @param Request $request
     * 企业支付
     */
    public function withdraw_wechat($finance_id)
    {
        try {
            $withDrawOrder = Db::table('ad_finance')->where(['id' => $finance_id])->field([
                'trade_no',
                'bank_card_num',
                'username',
                'withdraw_money',
                'bank_code'
            ])->find();

            $params           = new \Yurun\PaySDK\Weixin\Params\PublicParams;
            $params->appID    = 'wxd38af918cc55bb7c';
            $params->mch_id   = '1410856402';
            $params->key      = 'heilongjiangQingqiyunxiehehai001';
            $params->certPath = ROOT_PATH . 'public/cert_withdraw/apiclient_cert.pem';
            $params->keyPath  = ROOT_PATH . 'public/cert_withdraw/apiclient_key.pem';


            // SDK实例化，传入公共配置
            $sdk                        = new \Yurun\PaySDK\Weixin\SDK($params);
            $request                    = new \Yurun\PaySDK\Weixin\CompanyPay\Bank\Pay\Request;
            $request->rsaPublicCertFile = ROOT_PATH . 'public/cert_withdraw/public-1410856402.pem'; // 设置证书路径，用于加密银行卡号、姓名、开户行
            $request->partner_trade_no  = $withDrawOrder['trade_no']; // 订单号
            $request->enc_bank_no       = $withDrawOrder['bank_card_num'];//银行卡号
            $request->enc_true_name     = $withDrawOrder['username'];//银行卡对应的真实姓名
            $request->bank_code         = $withDrawOrder['bank_code'];//银行编码
            $request->amount            = (int)($withDrawOrder['withdraw_money'] * 100);
            $request->desc              = 'HYH区块链广告平台提现';
            $result                     = $sdk->execute($request);
            $verify_result              = $sdk->checkResult();

            if ($result['return_code'] == 'SUCCESS' && $verify_result) {
                return true;
            }
        } catch (\think\Exception $exception) {
            dump($exception->getMessage());
            die;
            return false;
        }
    }

    /**
     * @return \think\response\Json
     * 查询充值订单
     */
    public function check_withdraw()
    {

        $allWithDrawOrder = Db::table('ad_finance')->where([
            'progress' => 3,
            'withdraw_status' => 0,
            'status' => 3
        ])->field(['trade_no', 'id'])->select();

        foreach ($allWithDrawOrder as $item => $value) {
            // 公共配置
            $params           = new \Yurun\PaySDK\Weixin\Params\PublicParams;
            $params->appID    = 'wxd38af918cc55bb7c';
            $params->mch_id   = '1410856402';
            $params->key      = 'heilongjiangQingqiyunxiehehai001';
            $params->certPath = ROOT_PATH . 'public/cert_withdraw/apiclient_cert.pem';
            $params->keyPath  = ROOT_PATH . 'public/cert_withdraw/apiclient_key.pem';

            // SDK实例化，传入公共配置
            $sdk = new \Yurun\PaySDK\Weixin\SDK($params);

            $request                   = new \Yurun\PaySDK\Weixin\CompanyPay\Bank\Query\Request;
            $request->partner_trade_no = $value['trade_no']; // 订单号
            $result                    = $sdk->execute($request);
            $verify_result             = $sdk->checkResult();
            if ($result['status'] == 'SUCCESS' && $verify_result) {
                //更新提现状态
                Db::table('ad_finance')->where(['id' => $value['id']])->update([
                    'withdraw_status' => 1,
                    'bank_payment_no' => 'payment_no'
                ]);
            }
        }
        return json(['code' => 200, 'info' => '已获取到数据', 'data' => 'success']);
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 获取用户充值
     */
    public function getUserRecharge(Request $request)
    {
        $data['finance_id'] = $request->param('id');
        $finance_data       = Db::table('ad_finance')->find($data['finance_id']);
        if (empty($finance_data)) {
            $this->success('找不到提现单号');
        }

        $result                     = Db::table('ad_banner_money')->where(['uid' => $finance_data['uid']])->select();
        $user_info                  = Db::table('ad_user_info')->where(['uid' => $finance_data['uid']])->find();
        $user_info['province_name'] = Db::table('ad_provinces')->where(['provinceid' => $user_info['province']])->value('province');
        $user_info['city_name']     = Db::table('ad_cities')->where(['cityid' => $user_info['city']])->value('city');

        foreach ($result as $item => $value) {
            $result[$item]['province_name'] = $user_info['province_name'];
            $result[$item]['city_name']     = $user_info['city_name'];
            $result[$item]['true_name']     = $user_info['true_name'];
            $result[$item]['phone']         = $user_info['phone'];
            $result[$item]['earn']          = $user_info['earn'];
            $result[$item]['withDrawMoney'] = $finance_data['withdraw_money'];
        }
        return json(['code' => 200, 'info' => 'success', 'data' => $result]);
    }

    /**
     * @param Request $request
     * 总收益
     */
    public function getStatData(Request $request)
    {
        $start_time = $request->param('start_time') ?: '';
        $end_time   = $request->param('end_time') ?: '';
        $where      = [];
        $days       = 0;
        if ($start_time && $end_time) {
            $time1                = strtotime($start_time);
            $time2                = strtotime($end_time);
            $where['create_time'] = ['between', "$time1,$time2"];
        }

        $recharge = Db::table('ad_banner_money')->where($where)->sum('money');
        $withdraw = Db::table('ad_finance')->where($where)->sum('withdraw_money');
        dd($recharge, $withdraw);
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 充值echars
     */
    public function getRecharge(Request $request)
    {
        $start_time = $request->param('start_time') ?: '';
        $end_time   = $request->param('end_time') ?: '';


        $where = [];
        $days  = $request->param('days') ?: 0;
        if ($start_time && $end_time) {
            $time1                = strtotime($start_time);
            $time2                = strtotime($end_time);
            $where['create_time'] = ['between', "$time1,$time2"];
            $days                 = daysbetweendates($start_time, $end_time);
        }

        $all_month = [];
        for ($i = $days ?: 7; $i > 0; $i--) {
            $str_time = getDay7TimeStamps($end_time, $i);

            $k           = date("m", $str_time['lastday']);
            $all_month[] = $k . '-' . date("d", $str_time['lastday']);

            $data[$k . '-' . $i]['recharge'] = Db::table('ad_user_money')
                ->where('create_time', 'between', [$str_time['firstday'], $str_time['lastday']])
                ->where(['status' => 1])
                ->sum('money');

        }


        $output     = [];
        $all_data   = [];
        $final_data = [];

        foreach ($data as $k => $v) {
            $output['recharge'][]      = ($v['recharge']);
            $all_data['caculate_data'] = $output;
        }

        foreach ($all_data['caculate_data'] as $k => $v) {
            if ($k == 'recharge') {
                $final_data[$k]['name'] = '收益';
                $final_data[$k]['type'] = 'line';
                $final_data[$k]['data'] = $v;
            }
        }

        $final_data               = array_values($final_data);
        $return_data['all_data']  = $final_data;
        $return_data['all_month'] = $all_month;
        $return_data['chinese']   = ['收益'];
        return json(['code' => 200, 'data' => $return_data]);
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 提现echars
     */
    public function getWithDraw(Request $request)
    {
        $start_time = trim($request->param('start_time')) ?: '';
        $end_time   = trim($request->param('end_time')) ?: '';

        $where = [];
        $days  = $request->param('days') ?: 0;
        if ($start_time && $end_time) {
            $time1 = strtotime($start_time);
            $time2 = strtotime($end_time);

            $where['create_time'] = ['between', "$time1,$time2"];
            $days                 = daysbetweendates($start_time, $end_time);
        }

        $all_month = [];
        for ($i = $days ?: 7; $i > 0; $i--) {
            $str_time                        = getDay7TimeStamps($end_time, $i);
            $k                               = date("m", $str_time['lastday']);
            $all_month[]                     = $k . '-' . date("d", $str_time['lastday']);
            $data[$k . '-' . $i]['recharge'] = Db::table('ad_finance')
                ->where('create_time', 'between', [$str_time['firstday'], $str_time['lastday']])
                ->where(['withdraw_status' => 1])
                ->sum('withdraw_money');
        }

        $output     = [];
        $all_data   = [];
        $final_data = [];

        foreach ($data as $k => $v) {
            $output['recharge'][]      = ($v['recharge']);
            $all_data['caculate_data'] = $output;
        }
        foreach ($all_data['caculate_data'] as $k => $v) {
            if ($k == 'recharge') {
                $final_data[$k]['name'] = '支出';
                $final_data[$k]['type'] = 'line';
                $final_data[$k]['data'] = $v;
            }
        }
        $final_data               = array_values($final_data);
        $return_data['all_data']  = $final_data;
        $return_data['all_month'] = $all_month;
        $return_data['chinese']   = ['支出'];
        return json(['code' => 200, 'data' => $return_data]);
    }

    /**
     * @return mixed
     * 测试银行卡
     */
    public function testVerifyBank()
    {
        $key      = 'dd451c55b8afb08f33dad90ae7f55fa8';
        $realname = '盛伟';//姓名
        $idcard   = '430121222233334444';//身份证
        $bankcard = '6227002922080354331';//银行卡
        $mobile   = '15399900130';//手机号
        $url      = "http://v.juhe.cn/verifybankcard4/query.php?key=$key&bankcard=$bankcard&realname=$realname&idcard=$idcard&mobile=$mobile";

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        $result = json_decode($res, true);
        if (!empty($result['resultcode'])) {
            return json(['code' => 500, 'info' => $result['reason']]);
        }

        if ($result["error_code"] == 0 && $result['result']['res'] == 1) {
            return json(['code' => 200, 'info' => 'success']);
        }

        if ($result["error_code"] == 0 && $result['result']['res'] != 1) {
            return json(['code' => 500, 'info' => $result['result']['res']['message']]);
        }

        return json(['code' => 500, 'info' => $result['reason']]);
    }


    public function verifyBank($cardNo, $bank_code)
    {
        try {
            $url    = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json"
                . "?_input_charset=utf-8&cardNo={$cardNo}&cardBinCheck=true";

            $content  = file_get_contents($url);
            $bankInfo = json_decode($content, true);

            $bank_arr = [
                1002 => 'ICBC',
                1005 => 'ABC',
                1026 => 'BOC',
                1003 => 'CCB',
                1001 => 'CMB',
                1066 => 'PSBC',
                1020 => 'COMM',
                1004 => 'SPDB',
                1006 => 'CMBC',
                1009 => 'CIB',
                1010 => 'SPABANK',
                1021 => 'CITIC',
                1025 => 'HXBANK',
                1027 => 'GDB',
                1022 => 'CEB',
                1032 => 'BJBANK',
                1056 => 'NBBANK',
            ];
            if ($bank_arr[$bank_code] != $bankInfo['bank']) {
                return false;
            }
            return true;
        } catch (\think\Exception $exception) {
            return false;
        }
    }


}
